import time
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://search.suning.com/%E7%A9%BA%E8%B0%83/")
time.sleep(3)
i = 0
while True:
    i += 1
    time.sleep(3)
    driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    time.sleep(5)
    data_information_list = driver.find_elements("xpath", "//ul[@class='general clearfix']/li/div[@class='item-bg']")
    for data_information in data_information_list:
        data_list = []
        data_title = data_information.find_element("xpath",
                                                   ".//div[@class='res-info']/div[@class='title-selling-point']").text
        data_list.append(data_title)
        data_url = data_information.find_element("xpath",
                                                 ".//div[@class='res-info']/div[@class='title-selling-point']/a").get_attribute(
            "href")
        data_list.append(data_url)
        try:
            data_evaluate_num = data_information.find_element("xpath", ".//div[@class='info-evaluate']/a/i").text
        except:
            data_evaluate_num = "0"
        data_list.append(data_evaluate_num)
        print(data_list)
        data_list = ",".join(data_list)
        with open("./苏宁易购/数据.txt", "a", encoding="utf-8") as f:
            f.write(data_list + "\n")  # 写入
    time.sleep(3)
    with open("./苏宁易购/数据.txt", "a", encoding="utf-8") as f:
        f.write(f"第{i}页" + "\n")  # 写入文件
    print(f"第{i}页")
    driver.execute_script("window.scrollBy(0, -500);")
    time.sleep(5)
    element = driver.find_element("xpath", "//a[@id='nextPage']")
    try:
        element.click()
    except:
        break
